import React, { useEffect, useMemo, useState } from "react"
import Taro, { useDidShow } from "@tarojs/taro"
import { Button, Image, View } from "@tarojs/components"
import { AtIcon } from "taro-ui"
import orderIcon from "../../assets/images/order-icon.png"
import serviceIcon from "../../assets/images/service-icon.png"
import bgImage from "../../assets/images/mine-bg.png"
import defaultImg from "../../assets/images/default.png"
import "./index.scss"
import { checkIsLogin, getToken, setLoginUser } from "../../utils"
import http from "../../utils/http"

export default function () {
  const [top, setTop] = useState()
  const [userInfo, setUserInfo] = useState()
  useEffect(() => {
    /// 顶部距离调整
    var { top: t } = Taro.getMenuButtonBoundingClientRect()
    setTop(t + 18)
  }, [])

  const getUserInfo = async () => {
    const { data } = await http.get("/core/user/getUserInfoAndRefreshSession")
    if (data) {
      setUserInfo({
        ...data,
      })
      setLoginUser({
        ...data,
      })
    }
  }

  const menuList = useMemo(() => {
    const menu = [
      {
        title: "订单管理",
        icon: orderIcon,
        onClick: null,
        children: [
          {
            title: "预约单",
            onClick: () => checkIsLogin() && Taro.navigateTo({ url: "/pages/order/index?tabCurrent=0" }),
          },
          {
            title: "历史订单",
            onClick: () => checkIsLogin() && Taro.navigateTo({ url: "/pages/order/index?tabCurrent=1" }),
          },
        ],
      },
      {
        title: "联系客服",
        icon: serviceIcon,
        onClick: () => {
          Taro.makePhoneCall({
            phoneNumber: "13818144484",
          })
        },
        children: null,
      },
    ]
    if (userInfo && userInfo?.role != 0) {
      menu[0].children = [
        {
          title: "用户订单管理",
          onClick: () =>
            checkIsLogin() &&
            Taro.navigateTo({
              url: "/pages/adminOrder/index",
            }),
        },
      ]
    }
    return menu
  }, [userInfo])

  const login = e => {
    Taro.showLoading()
    const rawData = JSON.parse(e.detail.rawData)
    Taro.login({
      success: async function (res) {
        if (res.code) {
          const { data } = await http.post("/core/login/wechatLogin", {
            userRole: "0",
            wxcode: res.code,
          })
          Taro.setStorageSync("sessionId", data.sessionId)
          await http.post("/core/user/updateUserInfo", {
            userName: rawData.nickName,
            avatar: rawData.avatarUrl,
          })
          onButtonGetUserinfo()
          Taro.showToast({
            title: "登录成功",
            icon: "success",
          })
        } else {
          console.log("登录失败！" + res.errMsg)
        }
      },
      fail: function (res) {
        console.log(res)
      },
    })
  }

  const onButtonGetUserinfo = async () => {
    const { data } = await http.get("/core/user/getUserInfoAndRefreshSession")
    if (data) {
      setLoginUser(data)
      getUserInfo()
    }
  }

  useDidShow(() => {
    Taro.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#000000",
    })
    getToken() && getUserInfo()
  })

  return (
    <View className="page-mine">
      <View className="header" style={{ paddingTop: top + "px" }}>
        <Image src={bgImage} className="header-bg"></Image>
        <View className="info">
          <View className="info-left">
            <View className="name">hello，{userInfo?.userName || "请登录"}</View>
            {userInfo ? (
              <View className="subtitle">小小羽毛球，乐趣无尽头。</View>
            ) : (
              <Button className="login-btn" openType="getUserInfo" onGetUserInfo={login}>
                登录
              </Button>
            )}
          </View>
          <Image className="info-photo" src={userInfo?.avatar || defaultImg}></Image>
        </View>
      </View>
      <View className="list">
        {menuList.map(item1 => {
          return (
            <View key={item1.title} className="list-item">
              <View
                className="first-title"
                onClick={() => {
                  item1.onClick && item1.onClick()
                }}
              >
                <Image src={item1.icon} className="title1-icon"></Image>
                <View className="title1-text">{item1.title}</View>
                {item1.onClick && <AtIcon value="chevron-right" size={16}></AtIcon>}
              </View>
              {item1.children?.length > 0 && (
                <View className="list-card">
                  {item1.children.map(item2 => (
                    <View
                      className="title2-item"
                      key={item2.title}
                      onClick={() => {
                        item2.onClick && item2.onClick()
                      }}
                    >
                      <View className="title2-item-text">{item2.title}</View>
                      <AtIcon value="chevron-right" size={16}></AtIcon>
                    </View>
                  ))}
                </View>
              )}
            </View>
          )
        })}
      </View>
    </View>
  )
}
